package com.danhuang.cloud.danhuangfile.service;

import cn.hutool.core.io.IoUtil;
import cn.hutool.json.JSONUtil;
import com.danhuang.cloud.danhuangcore.constant.ResConstant;
import com.danhuang.cloud.danhuangcore.model.DhRes;
import com.danhuang.cloud.danhuangcore.service.FileDubboService;
import com.danhuang.cloud.danhuangfile.config.MinioTemplate;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@DubboService
@Slf4j
public class FileDubboServiceImpl implements FileDubboService {

    @Resource
    private MinioTemplate minioTemplate;

    @Override
    public DhRes test(String a, String b) {
        return DhRes.success(a+b);
    }

    @Override
    public DhRes uploader(String path, byte[] bytes) {
        try{
            List<String> filePath = Arrays.stream(path.split("-",2)).collect(Collectors.toList());
            String bucket = filePath.get(0);
            String fileName = filePath.get(1);
            minioTemplate.fileUploader(bucket, fileName, IoUtil.toStream(bytes));
            return DhRes.success();
        }catch (Exception e){
            log.error("上传异常",e);
            return DhRes.fail(ResConstant.SYSTEM_ERROR_CODE);
        }
    }

    @Override
    public byte[] down(String path) {
        try{
            List<String> filePath = Arrays.stream(path.split("-",2)).collect(Collectors.toList());
            String bucket = filePath.get(0);
            String fileName = filePath.get(1);
            return IoUtil.readBytes(minioTemplate.fileDowner(bucket, fileName));
        }catch (Exception e){
            log.error("下载异常",e);
            return null;
        }
    }
}
